//
//  HZRefreshControl.swift
//  HansWeibo
//
//  Created by Hans on 16/8/17.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit
// 刷新控件的状态
enum HZRefreshControlState: Int {
    // 正常
    case Normal = 0
    // 下拉中
    case Pulling = 1
    // 刷新
    case Prfreshing = 2
}
// 控件的高度
private let HZRefreshControlH: CGFloat = 50

class HZRefreshControl: UIControl {
    
    // 记录滑动视图
    var scrollView: UIScrollView?
    
    // 记录状态
    var hzState: HZRefreshControlState = .Normal{
        
        didSet{
            switch hzState {
            case .Normal:
                messageLabel.text = "正常"
                UIView.animateWithDuration(0.25, animations: {
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                if oldValue == .Prfreshing {
                    UIView.animateWithDuration(0.25, animations: {
                        self.scrollView?.contentInset.top -= HZRefreshControlH
                        }, completion: { (_) in
                            // 结束动画
                            self.activity.stopAnimating()
                            self.pullImageView.hidden = false
                    })
                }
                
            case .Pulling:
                messageLabel.text = "下拉中"
                UIView.animateWithDuration(0.25, animations: {
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI*3))
                })
            case .Prfreshing:
                messageLabel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: { 
                    self.scrollView?.contentInset.top += HZRefreshControlH
                    }, completion: { (_) in
                        self.pullImageView.hidden = true
                        // 开始动画
                        self.activity.startAnimating()
                        // 告知外界刷新
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -HZRefreshControlH, width: SCREENW, height: HZRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 供外界调用 结束刷新
    func endRefreshing(){
        hzState = .Normal
    }
    
    // 设置视图
    private func setupUI(){
        backgroundColor = AppTheneColor
        // 添加控件
        addSubview(messageLabel)
        addSubview(activity)
        addSubview(pullImageView)
        // 添加约束
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        activity.translatesAutoresizingMaskIntoConstraints = false
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        // 添加约束
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: activity, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: activity, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
    }
    
 
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        // 判断是否为nil 是否可以转成uiscrollView  
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        self.scrollView = scrollView
        // 使用KVO 注册观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    // 观察者实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 记录scrollView滚动
        let contentOffsetY = self.scrollView?.contentOffset.y
        // 顶部滑动的距离
        let contentInsetTop = self.scrollView!.contentInset.top
        
        // 拖动中 true
        if scrollView!.dragging {
            if contentOffsetY > -(contentInsetTop+HZRefreshControlH) && hzState == .Pulling{
                // 正常
                hzState = .Normal
                
            }else if contentOffsetY <= -(contentInsetTop+HZRefreshControlH) && hzState == .Normal{
                // 下拉中
                hzState = .Pulling
                
            }

        }else {
            // 松手了
            if hzState == .Pulling {
                hzState = .Prfreshing
                
            }
        }
        
    }
    
    // MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
       let label = UILabel()
        label.text = "正常"
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(15)
        return label
    }()
    // 菊花
    private lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView()
    // 箭头
    private lazy var pullImageView :UIImageView = UIImageView(imageName: "tableview_pull_refresh")
    
    // KVO移除
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}




